import { Provide } from "@midwayjs/core";
import { BaseService, CoolCommException, CoolTransaction } from "@cool-midway/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository, QueryRunner } from "typeorm";
import { OrderLogisticsEntity } from "../../order/entity/logistics";
import { OrderItemEntity } from "../../order/entity/item";

/**
 * 物流服务
 */
@Provide()
export class OrderLogisticsService extends BaseService {
    @InjectEntityModel(OrderLogisticsEntity)
    orderLogisticsEntity: Repository<OrderLogisticsEntity>;

    @InjectEntityModel(OrderItemEntity)
    orderItemEntity: Repository<OrderItemEntity>;

    /**
     * 仅绑定/更新快递单号与公司；要求该子项已有物流收货信息记录
     */
    @CoolTransaction()
    async bindTracking(
        params: { itemId: number; company?: string; trackingNo?: string },
        queryRunner?: QueryRunner
    ) {
        const { itemId, company, trackingNo } = params || ({} as any);
        if (!itemId) throw new CoolCommException('缺少 itemId');

        const item = await queryRunner.manager.findOne(OrderItemEntity, { where: { id: itemId } });
        if (!item) throw new CoolCommException('订单子项不存在');

        const logistics = await queryRunner.manager.findOne(OrderLogisticsEntity, { where: { itemId } });
        if (!logistics) throw new CoolCommException('尚未创建收货信息，无法绑定物流单号');

        await queryRunner.manager.update(
            OrderLogisticsEntity,
            { id: logistics.id },
            { company: company || null, trackingNo: trackingNo || null }
        );
        return true;
    }
}


